<template>
  <div>
    <!-- 绘制form的静态页 -->
    <!-- 4.使用info -->
    <el-dialog
      :title="info.isAdd?'商品添加':'商品编辑'"
      :visible.sync="info.isshow"
      @closed="close"
      @opened="opened"
    >
      <el-form :model="form">
        {{form}}
        <el-form-item label="一级分类" label-width="120px">
          <el-select v-model="form.first_cateid" @change="change_first_cateid">
            <el-option label="请选择" value disabled></el-option>
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" label-width="120px">
          <el-select v-model="form.second_cateid">
            <el-option label="请选择" value disabled></el-option>
            <el-option
              v-for="item in second_cate_list"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" label-width="120px">
          <el-input v-model="form.goodsname"></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="120px">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" label-width="120px">
          <el-input v-model="form.market_price"></el-input>
        </el-form-item>
        <el-form-item label="图片" label-width="120px">
          <!-- 这里是个图片 -->
          <div class="my-upload">
            <h3>+</h3>
            <img v-if="imgUrl" :src="imgUrl" alt />
            <input type="file" @change="changefile" />
          </div>
        </el-form-item>

        <el-form-item label="商品规格" label-width="120px">
          <el-select v-model="form.specsid" @change="change_specs_id">
            <el-option label="请选择" value disabled></el-option>
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品属性" label-width="120px">
          <el-select v-model="form.specsattr" multiple>
            <el-option label="请选择" value disabled></el-option>
            <el-option v-for="item in attrsArr" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" label-width="120px">
          <el-radio v-model="form.isnew" :label="1">是</el-radio>
          <el-radio v-model="form.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" label-width="120px">
          <el-radio v-model="form.ishot" :label="1">是</el-radio>
          <el-radio v-model="form.ishot" :label="2">否</el-radio>
        </el-form-item>

        <el-form-item label="状态" label-width="120px">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="2"></el-switch>
        </el-form-item>
        <el-form-item label="商品描述" label-width="120px">
          <!-- 富文本编辑器 -->
          <div id="editor"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="add" v-if="info.isAdd">添 加</el-button>
        <el-button type="primary" v-else @click="update">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import E from "wangeditor";
import { mapGetters, mapActions } from "vuex";
import {
  reqcatelist,
  reqgoodsadd,
  reqgoodsedit,
  reqgoodsinfo,
} from "../../../request/api";
import { errorAlert, successAlert } from "../../../utils/alert";
import path from "path";
export default {
  // 3.收info
  props: ["info"],
  data() {
    return {
      //表单数据
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 1,
        ishot: 1,
        status: 1,
      },
      //二级分类的list
      second_cate_list: [],
      //图片临时地址
      imgUrl: "",
      //属性数组list
      attrsArr: [],
    };
  },
  computed: {
    ...mapGetters({
      //分类列表
      cateList: "fenlei/list",
      //规格列表
      specsList: "guige/list",
    }),
  },
  mounted() {
    // 如果没有请求一级分类，就请一次
    if (this.cateList.length == 0) {
      this.reqCateList();
    }
    // 如果没有请求规格，就请一次
    this.reqSpecsList(true);
  },
  methods: {
    ...mapActions({
      //请求分类list
      reqCateList: "fenlei/reqList",
      //请求规格list
      reqSpecsList: "guige/reqList",
      // 商品列表和总数
      reqList: "guanli/reqList",
      reqTotal: "guanli/reqTotal",
    }),
    // ====================
    // 一级分类变了 
    change_first_cateid() {
      // 清空二级分类
      this.form.second_cateid = "";
      this.get_second_cate_list();
    },
    //获取2级分类list
    get_second_cate_list() {
      // 根据一级分类获取二级分类的list
      reqcatelist({ pid: this.form.first_cateid }).then((res) => {
        let list = res.data.list ? res.data.list : [];
        this.second_cate_list = list;
      });
    },
    //图片
    changefile(e) {
      let file = e.target.files[0];
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件最大2M");
        return;
      }
      let extname = path.extname(file.name);
      let extArr = [".jpg", ".png", ".jpeg", ".gif"];
      if (extArr.indexOf(extname) == -1) {
        errorAlert("请上传图片");
        return;
      }
      this.imgUrl = URL.createObjectURL(file);
      this.form.img = file;
    },
    //商品规格变了
    change_specs_id() {
      // form上的属性重置
      this.form.specsattr = [];
      this.get_attrs_arr();
    },
    get_attrs_arr() {
      // 计算规格属性list
      let obj = this.specsList.find((item) => item.id == this.form.specsid);
      this.attrsArr = obj ? obj.attrs : []; //['15ml','30ml','45ml']
    },
    // dialog出现
    opened() {
      //创建编辑器对象
      this.editor = new E("#editor");
      this.editor.create();
      //赋值
      this.editor.txt.html(this.form.description);
    },

    // =========================
    //7.取消
    cancel() {
      this.info.isshow = false;
    },
    // 清空form
    empty() {
      //表单数据
      this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 1,
        ishot: 1,
        status: 1,
      };
      //二级分类的list
      this.second_cate_list = [];
      //图片临时地址
      this.imgUrl = "";
      //属性数组list
      this.attrsArr = [];
      this.editor.txt.html("");
    },
    //验空
    check() {
      return new Promise((resolve, reject) => {
        if (this.form.first_cateid == "") {
          errorAlert("一级分类不能为空");
          return;
        }
        if (this.form.second_cateid == "") {
          errorAlert("二级分类不能为空");
          return;
        }
        if (this.form.goodsname == "") {
          errorAlert("商品名称不能为空");
          return;
        }
        if (this.form.price == "") {
          errorAlert("价格不能为空");
          return;
        }

        if (this.form.market_price == "") {
          errorAlert("市场价格不能为空");
          return;
        }
        if (!this.form.img) {
          errorAlert("请上传图片");
          return;
        }
        if (this.form.specsid == "") {
          errorAlert("规格不能为空");
          return;
        }
        if (this.form.specsattr.length == 0) {
          errorAlert("规格属性不能为空");
          return;
        }
        if (this.editor.txt.html() == "") {
          errorAlert("描述不能为空");
          return;
        }
        resolve();
      });
    },
    //添加
    add() {
      this.check().then(() => {
        // 将编辑器的内容取出来给form.description
        this.form.description = this.editor.txt.html();
        // 2.将form发送给后端添加
        //发起添加请求
        reqgoodsadd({
          ...this.form,
          specsattr: this.form.specsattr.join(","),
        }).then((res) => {
          //添加成功
          if (res.data.code == 200) {
            // 1.弹成功
            successAlert(res.data.msg);
            // 2.清空form
            this.empty();
            // 3.弹框消失
            this.info.isshow = false;
            // 4.列表重新请求
            this.reqList();
            //请总数
            this.reqTotal();
          }
        });
      });
    },

    //获取一条数据
    getOne(id) {
      //取数据
      reqgoodsinfo({ id: id }).then((res) => {
        if (res.data.code == 200) {
          this.form = res.data.list;
          //补id
          this.form.id = id;
          //根据1级分类id，请求2级分类list
          this.get_second_cate_list();
          //将form.specsattrs变成数组
          this.form.specsattr = this.form.specsattr.split(",");

          //根据specsid计算attrsArr
          this.get_attrs_arr();
          //图片
          this.imgUrl = this.$pre + this.form.img;
          //给富文本编辑器赋值
          this.editor && this.editor.txt.html(this.form.description);
        }
      });
    },
    //修改
    update() {
      this.check().then(() => {
        // 将编辑器的内容取出来给form.description
        this.form.description = this.editor.txt.html();
        //修改请求
        reqgoodsedit({
          ...this.form,
          specsattr: this.form.specsattr.join(","),
        }).then((res) => {
          //修改成功
          if (res.data.code == 200) {
            // 1.弹成功
            successAlert(res.data.msg);
            // 2.表单清空
            this.empty();
            // 3.弹框消失
            this.info.isshow = false;
            // 4.列表更新
            this.reqList();
          }
        });
      });
    },
    //弹框关闭
    close() {
      // 是编辑，要清空表单
      !this.info.isAdd && this.empty();
    },
  },
};
</script>
<style scoped lang="less">
@import "../../../less/index.less";
.box {
  display: flex;
}
.el-input {
  flex: 1;
}
.my-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed @primary;
  position: relative;
}
.my-upload h3 {
  text-align: center;
  height: 100px;
  line-height: 100px;
  color: @header-color;
}
.my-upload input {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}
.my-upload img {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
</style>